<template>
  <div ref="spriteBox">
    <div ref="sprite" class="sprite"></div>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  PropType,
  reactive,
  ref,
  toRefs,
  watchEffect,
  defineProps,
  defineEmits
} from "vue";
import { spriteInterface } from "@/interface/index";
import { useFrameAnimation } from "./useFrameAnimation";

const props = defineProps({
  action: {
    type: Boolean,
    default: false,
  },
  spriteObj: Object as PropType<spriteInterface>,
})
const emit = defineEmits(['moveEnd'])
const spriteBox = ref(null) as Ref;
const sprite = ref() as Ref;
const spriteObj = reactive(props.spriteObj || {}) as spriteInterface;
const { width, height, url, length } = toRefs(spriteObj);
// 监听APP.vue传递的action是否为true,为true的话才开始"表演"
watchEffect(() => {
  if (props.action) {
    useFrameAnimation(
      spriteObj,
      sprite,
      spriteBox,
      () => {
        triggerMove();
      },
      () => {
        emit("moveEnd");
      }
    );
  }
});
// 给宽度后边加上单位
const widthRef = computed(() => {
  return width.value + "px";
});
// 给高度后边加上单位
const heightRef = computed(() => {
  return height.value + "px";
});
// 给背景图片连接添加url
const urlImg = computed(() => {
  return `url("${url.value}")`;
});
// 移动到目标位置
function triggerMove() {
  if (spriteObj.scale || spriteObj.scale === 0) {
    spriteBox.value.style.transform = `scale(${spriteObj.scale})`;
  }
  if (spriteObj.endPosition) {
    Object.keys(spriteObj.endPosition).forEach((o) => {
      if (spriteBox.value && sprite.value.style) {
        spriteBox.value.style[o] = spriteObj.endPosition[o];
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.sprite {
  width: v-bind(widthRef);
  height: v-bind(heightRef);
  background-image: v-bind(urlImg);
  background-repeat: no-repeat;
  background-position: 0;
  background-size: cover;
}
</style>
